package com.chaopei.znpk.controller;

import com.alibaba.fastjson.JSON;
import com.chaopei.znpk.entity.Class;
import com.chaopei.znpk.mapper.ClassMapper;
import com.chaopei.znpk.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Zyb
 * @Date 2022/5/26 9:38
 */
@RestController
@CrossOrigin
@RequestMapping("classExcel")
public class ClassController {

    @Autowired
    ClassService classService;

    /***
     *  下载班级信息Excel表数据
     * @param response
     * @throws IOException
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        classService.download(response);
    }

    /***
     * 上传班级信息excel到数据库
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Map<String,Object> upload(@RequestParam("file") MultipartFile file) throws IOException {

        Map<String,Object> map = new HashMap<>();
        try {
            classService.upload(file);
            map.put("status",true);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            map.put("status",false);
            return map;
        }
    }

    /***
     * 下载班级 excel模板
     * @param response
     * @throws IOException
     */
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        classService.downloadTemplate(response);
    }

    /***
     * 添加一条班级信息
     * @param aClass
     * @return
     */
    @PostMapping("/addClasses")
    public Map<String,Object> addClasses(@RequestBody Class aClass){
        System.out.println(aClass.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            classService.addClasses(aClass);
            map.put("status",true);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status",false);
            return map;
        }
    }

    @Resource
    ClassMapper classMapper;
    @RequestMapping("/selectClassAll")
    public String selectClasses(){
        List<Class> aClasses = classMapper.selectClassesAll();
        String str = JSON.toJSONString(aClasses);
        return str;
    }
}
